package com.pactera.madp.cp.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pactera.madp.admin.api.dto.SyncSysDept;
import com.pactera.madp.admin.api.entity.SysDept;
import com.pactera.madp.admin.api.feign.RemoteSyncSysService;
import com.pactera.madp.admin.api.feign.RemoteUserService;
import com.pactera.madp.common.core.constant.CommonConstants;
import com.pactera.madp.common.core.constant.SecurityConstants;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.cp.api.entity.WorkContactEmployeeEntity;
import com.pactera.madp.cp.api.entity.WorkDeptEntity;
import com.pactera.madp.cp.api.entity.WorkEmployeeDepartmentEntity;
import com.pactera.madp.cp.api.entity.WorkEmployeeEntity;
import com.pactera.madp.cp.api.dto.emp.WXEmployeeDTO;
import com.pactera.madp.cp.config.WxAvatarUploadConfig;
import com.pactera.madp.cp.mapper.WorkDeptMapper;
import com.pactera.madp.cp.mapper.WorkEmployeeMapper;
import com.pactera.madp.cp.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.pactera.madp.cp.common.constant.WxCallbackConst.*;

@Slf4j
@Service
@Transactional(rollbackFor = {RuntimeException.class, Exception.class})
public class WxCallbackEmployeeServiceImp implements IWxCallbackEmployeeService {

    @Autowired
    private WorkDeptMapper workDeptMapper;
    @Autowired
    private WorkEmployeeMapper workEmployeeMapper;
    @Autowired
    private IWorkDeptService deptService;
    @Autowired
    private IWorkEmployeeService employeeService;
    @Autowired
    private IWorkEmployeeDepartmentService employeeDepartmentService;
    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private RemoteSyncSysService remoteSyncSysService;
    @Autowired
    private WxAvatarUploadConfig wxAvatarUploadConfig;
    @Autowired
    private IWorkContactEmployeeService workContactEmployeeService;

    @Override
    public String dispatchEvent(String dataJson) {
        JSONObject jsonObject = JSON.parseObject(dataJson);
        int corpId = jsonObject.getIntValue("corpId");
        JSONObject xmlJsonObject = jsonObject.getJSONObject("xml");
        String changeType = xmlJsonObject.getString("changetype");

        // 部门回调
        if (CHANGE_TYPE_DEPARTMENT_CREATE.equals(changeType)) {
            //return createDepartment(corpId, xmlJsonObject);
            return "";
        }
        if (CHANGE_TYPE_DEPARTMENT_UPDATE.equals(changeType)) {
            //return updateDepartment(corpId, xmlJsonObject);
            return "";
        }
        if (CHANGE_TYPE_DEPARTMENT_DELETE.equals(changeType)) {
            //return deleteDepartment(corpId, xmlJsonObject);
            return "";
        }

        // 员工回调
        if (CHANGE_TYPE_EMPLOYEE_CREATE.equals(changeType)) {
            //return createEmployee(corpId, xmlJsonObject);
            return "";
        }
        if (CHANGE_TYPE_EMPLOYEE_UPDATE.equals(changeType)) {
            return updateEmployee(corpId, xmlJsonObject);
        }
        if (CHANGE_TYPE_EMPLOYEE_DELETE.equals(changeType)) {
            //return deleteEmployee(corpId, xmlJsonObject);
            return "";
        }

        return "";
    }

    public String createDepartment(int corpId, JSONObject jsonObject) {
        int wxDepartmentId = jsonObject.getIntValue("id");
        String name = jsonObject.getString("name");
        int wxParentId = jsonObject.getIntValue("parentid");
        int order = jsonObject.getIntValue("order");

        WorkDeptEntity entity = new WorkDeptEntity();
        entity.setWxDepartmentId(wxDepartmentId);
        entity.setCorpId(corpId);
        entity.setName(name);
        entity.setParentId(getMainDepartmentId(corpId, wxParentId));
        entity.setWxParentid(wxParentId);
        entity.setOrder(order);
        workDeptMapper.insert(entity);

        List<WorkDeptEntity> depts = new ArrayList<>();
        depts.add(entity);
        deptService.insertDeptments(depts, corpId);

        //同步到系统
        syncDetpToSys(entity, 0, "新增");

        return "success";
    }

    public String updateDepartment(int corpId, JSONObject jsonObject) {
        int wxDepartmentId = jsonObject.getIntValue("id");
        String name = jsonObject.getString("name");
        Integer wxParentId = jsonObject.getInteger("parentid");
        int order = jsonObject.getIntValue("order");

        WorkDeptEntity entity = new WorkDeptEntity();
        entity.setWxDepartmentId(wxDepartmentId);
        entity.setOrder(order);
        entity.setCorpId(corpId);

        entity = workDeptMapper.selectOne(new QueryWrapper<>(entity));
        if (name != null) {
            entity.setName(name);
        }
        if (wxParentId != null) {
            entity.setParentId(getMainDepartmentId(corpId, wxParentId));
            entity.setWxParentid(wxParentId);
        }
        workDeptMapper.updateById(entity);

        //同步到系统
        syncDetpToSys(entity, 1, "更新");

        return "success";
    }

    public String deleteDepartment(int corpId, JSONObject jsonObject) {
        int wxDepartmentId = jsonObject.getIntValue("id");
        WorkDeptEntity entity = new WorkDeptEntity();
        entity.setWxDepartmentId(wxDepartmentId);
        entity.setCorpId(corpId);

        entity = workDeptMapper.selectOne(new QueryWrapper<>(entity));
        workDeptMapper.deleteById(entity.getId());

        //同步到系统
        syncDetpToSys(entity, 2, "删除");

        return "success";
    }

    public String createEmployee(int corpId, JSONObject jsonObject) {
        List<Integer> integers = new ArrayList<>();

        WXEmployeeDTO dto = new WXEmployeeDTO();
        dto.setUserid(jsonObject.getString("userid"));
        dto.setName(jsonObject.getString("name"));

        String[] depts = jsonObject.getString("department").split(",");
        for (String s : depts) {
            integers.add(Integer.parseInt(s));
        }
        dto.setDepartment(integers);

        dto.setPosition(jsonObject.getString("position"));
        dto.setMobile(jsonObject.getString("mobile"));
        dto.setGender(jsonObject.getIntValue("gender"));
        dto.setEmail(jsonObject.getString("email"));
        dto.setAvatar(jsonObject.getString("avatar"));
        dto.setStatus(jsonObject.getIntValue("status"));
        dto.setIsleader(jsonObject.getIntValue("isleader"));

        JSONArray extattrArray = jsonObject.getJSONArray("extattr");
        List<String> attrList = new ArrayList<>();
        if (extattrArray != null && !extattrArray.isEmpty()) {
            for (int i = 0; i < extattrArray.size(); i++) {
                attrList.add(extattrArray.getString(i));
            }
        }
        JSONObject extattrJson = new JSONObject();
        extattrJson.put("attrs", attrList);
        dto.setExtattr(extattrJson.toJSONString());

        dto.setTelephone(jsonObject.getString("telephone"));

        integers.clear();
        dto.setOrder(integers);

        dto.setMainDepartment(jsonObject.getIntValue("maindepartment"));
        dto.setQrCode(jsonObject.getString("qrcode"));
        dto.setAlias(jsonObject.getString("alias"));

        integers.clear();
        String[] isleaderindepts = jsonObject.getString("isleaderindept").split(",");
        for (String s : isleaderindepts) {
            integers.add(Integer.parseInt(s));
        }
        dto.setIsLeaderInDept(integers);

        dto.setAddress(jsonObject.getString("address"));

        employeeService.insertEmployee(corpId, dto);

        //同步系统用户
        employeeService.syncSysUser(corpId, jsonObject.getString("userid"), CommonConstants.STATUS_NORMAL);

        return "success";
    }

    public String updateEmployee(int corpId, JSONObject jsonObject) {
        List<Integer> integers = new ArrayList<>();

        String wxUserId = jsonObject.getString("userid");
        WorkEmployeeEntity entity = new WorkEmployeeEntity();
        entity.setCorpId(corpId);
        entity.setWxUserId(wxUserId);
        entity = employeeService.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery(entity),false);
        if (entity == null) {
            log.error(" >>> 微信回调: 更新成员时, 成员不存在." + jsonObject.toJSONString());
            return "success";
        }

        String newWxUserId = jsonObject.getString("newuserid");
        if (newWxUserId != null) {
            wxUserId = newWxUserId;
            entity.setWxUserId(wxUserId);
        }

        String name = jsonObject.getString("name");
        if (name != null) {
            entity.setName(name);
        }

        String mobile = jsonObject.getString("mobile");
        if (mobile != null) {
            entity.setMobile(mobile);
            // 关联子账户
            /*SysUser sysUser = new SysUser();
            sysUser.setPhone(mobile);
            R<UserInfo> result = remoteUserService.info(sysUser, SecurityConstants.FROM_IN);
            if(result != null && result.getData() != null) {
                sysUser = ((UserInfo)result.getData()).getSysUser();
                entity.setLogUserId(sysUser.getUserId());
            }*/
        }

        String status = jsonObject.getString("status");
        if (status != null) {
            entity.setStatus(Integer.parseInt(status));
        }

        String avatar = jsonObject.getString("avatar");
        if (avatar != null) {
            entity.setAvatar(avatar);
        }
        String thumbAvatar = jsonObject.getString("thumb_avatar");
        if (thumbAvatar != null) {
            entity.setThumbAvatar(thumbAvatar);
        }

        String alias = jsonObject.getString("alias");
        if (alias != null) {
            entity.setAlias(alias);
        }

        String telephone = jsonObject.getString("telephone");
        if (telephone != null) {
            entity.setTelephone(telephone);
        }

        String address = jsonObject.getString("address");
        if (address != null) {
            entity.setAddress(address);
        }

        JSONArray extattrArray = jsonObject.getJSONArray("extattr");
        if (extattrArray != null) {
            List<String> attrList = new ArrayList<>();
            for (int i = 0; i < extattrArray.size(); i++) {
                attrList.add(extattrArray.getString(i));
            }
            JSONObject extattrJson = new JSONObject();
            extattrJson.put("attrs", attrList);
            entity.setExtattr(extattrJson.toJSONString());
        }

        WXEmployeeDTO dto = new WXEmployeeDTO();
        String department = jsonObject.getString("department");
        integers.clear();
        if (department != null) {
            String[] depts = department.split(",");
            for (String s : depts) {
                integers.add(Integer.parseInt(s));
            }
        }
        dto.setDepartment(integers);

        String isleaderindept = jsonObject.getString("isleaderindept");
        integers.clear();
        if (isleaderindept != null) {
            String[] isleaderindepts = jsonObject.getString("isleaderindept").split(",");
            for (String s : isleaderindepts) {
                integers.add(Integer.parseInt(s));
            }
        }
        dto.setIsLeaderInDept(integers);

        String order = jsonObject.getString("order");
        integers.clear();
        if (order != null) {
            String[] orders = jsonObject.getString("order").split(",");
            for (String s : orders) {
                integers.add(Integer.parseInt(s));
            }
        }
        dto.setOrder(integers);

        workEmployeeMapper.updateById(entity);
        if (department != null) {
            dto.setUserid(wxUserId);
            employeeService.updateEmpDeptIndex(corpId, dto);
        }

        return "success";
    }

    public String deleteEmployee(int corpId, JSONObject jsonObject) {
        String userId = jsonObject.getString("userid");
        log.info("userId:"+userId);

        //先同步删除系统用户
        employeeService.syncSysUser(corpId, jsonObject.getString("userid"), CommonConstants.STATUS_DEL);

        //本地成员删除
        WorkEmployeeEntity entity = new WorkEmployeeEntity();
        entity.setCorpId(corpId);
        entity.setWxUserId(userId);
        entity = employeeService.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery().eq(WorkEmployeeEntity::getCorpId,corpId).eq(WorkEmployeeEntity::getWxUserId,userId));
        log.info("entity:"+entity);
        if (entity == null) {
            return "success";
        }
        employeeService.removeById(entity);

        //删除与外部联系人的关联
        workContactEmployeeService.remove(Wrappers.<WorkContactEmployeeEntity>lambdaQuery()
                .eq(WorkContactEmployeeEntity::getEmployeeId,entity.getId()));

        //删除与部门的关联
        employeeDepartmentService.remove(Wrappers.<WorkEmployeeDepartmentEntity>lambdaQuery()
                .eq(WorkEmployeeDepartmentEntity::getEmployeeId,entity.getId()));
        return "success";
    }

    private int getMainDepartmentId(int corpId, int wxDepartmentId) {
        if (wxDepartmentId == 0) {
            return 0;
        }
        WorkDeptEntity workDeptEntity = new WorkDeptEntity();
        workDeptEntity.setCorpId(corpId);
        workDeptEntity.setWxDepartmentId(wxDepartmentId);
        return workDeptMapper.selectOne(new QueryWrapper<>(workDeptEntity)).getId();
    }

    public String getThumbAvatar(String avatar) {
        if (avatar != null) {
            int index = avatar.lastIndexOf("/");
            return avatar.substring(0, index) + "/100";
        }
        return "";
    }

    //同步部门到系统 opt 0-新增 1-更新 2-删除
    private void syncDetpToSys(WorkDeptEntity entity, int opt, String desc) {
        try {
            R<SysDept> result = null;
            if(opt == 0) {
                result = remoteSyncSysService.getSysWxRelationById(entity.getWxParentid(), SecurityConstants.FROM_IN);
            }else {
                result = remoteSyncSysService.getSysWxRelationById(entity.getWxDepartmentId(), SecurityConstants.FROM_IN);
            }
            SysDept sysDept = result.getData();
            if(result.getCode()==0) {
                //设置上级部门
                SyncSysDept pNode = new SyncSysDept();
                if(opt == 0) {
                    pNode.setSysDeptId(sysDept.getDeptId());
                }else{
                    pNode.setSysDeptId(sysDept.getParentId());
                }
                pNode.setWxDeptId(entity.getWxParentid());
                //设置新增部门
                SyncSysDept node = new SyncSysDept();
                if(opt != 0) {
                    node.setSysDeptId(sysDept.getDeptId());
                    node.setSysParentDeptId(sysDept.getParentId());
                }
                node.setWxDeptId(entity.getWxDepartmentId());
                node.setWxParentDeptId(entity.getWxParentid());
                node.setDeptName(entity.getName());
                node.setOrder(entity.getOrder());
                node.setOpt(opt);

                //设置远程调用参数
                List<SyncSysDept> trees = new ArrayList<>();
                trees.add(node);
                Map<Integer,SyncSysDept> syncSysDeptMap = new HashMap<>();
                syncSysDeptMap.put(entity.getWxParentid(),pNode);
                syncSysDeptMap.put(entity.getWxDepartmentId(),node);

                //远程调用系统部门接口同步数据
                String jsonTrees = JSONUtil.toJsonStr(trees);
                String jsonSysnSysDeptMap = JSONUtil.toJsonStr(syncSysDeptMap);
                Map<String,String> param = new HashMap<>();
                param.put("trees",jsonTrees);
                param.put("syncDeptMap",jsonSysnSysDeptMap);
                remoteSyncSysService.onSyncWxDept(param, SecurityConstants.FROM_IN);
            }else {
                log.error("回调" + desc + "同步到系统部门失败!!!");
            }
        }catch (Exception e) {
            log.error("回调" + desc + "同步到系统部门失败!!!",e);
        }

    }

}
